import React, { FC, useState } from "react"
import { useDrag } from '@use-gesture/react'
import { pxToSecond } from "./utils/tools"

interface Props {
    secondWidth: number
}
const Index: FC<Props> = ({ secondWidth = 0 }) => {
    const [activeIndex, setActiveIndex] = useState(0)
    // const currentDom = useRef<any>(null)
    const [trackList, setTrackList] = useState(
        [
            { start: 0, end: 1, name: '1' },
            { start: 2, end: 4, name: '2' },
            { start: 5, end: 9, name: '33' },
            { start: 44, end: 45, name: '444' },
        ]
    )

    // 禁用页面滚动
    const disableScroll = () => document.body.style.overflow = 'hidden'
    const enableScroll = () => document.body.style.overflow = ''

    const handleClick = (index: number, event: any) => {
        setActiveIndex(index)
        // currentDom.current = event.target
    }

    const updateOriginTrackList = (index: number, newStart: number, newEnd: number) => {
        const updatedTrackList = [...trackList];
        updatedTrackList[index] = { ...updatedTrackList[index], start: newStart, end: newEnd };
        setTrackList(updatedTrackList);
      }

    // 更新数据，带前后边界检测
    const updateTrackList = (start: number, end: number) => {
        if (end - start < 1) return // 最小宽度限制
        // 复制 trackList 以更新
        // 左侧边界检测，限制 start 不能小于前一个元素的 end
        const prevTrack = trackList[activeIndex - 1]
        start = prevTrack ? Math.max(start, prevTrack.end) : Math.max(0, start)
        // 右侧边界检测，限制 end 不能超过下一个元素的 start
        const nextTrack = trackList[activeIndex + 1]
        if (nextTrack) end = Math.min(end, nextTrack.start)

        // 更新当前拖拽元素的 start 和 end
        updateOriginTrackList(activeIndex, start, end)
    };
    
    // 右侧拖拽
    const bindRight = useDrag(({ movement: [mx], memo = trackList[activeIndex].end, active, cancel }) => {
        active ? disableScroll() : enableScroll()
        if (activeIndex >= 0 && active) {
            const newEnd = memo + pxToSecond(mx, secondWidth)
            updateTrackList(trackList[activeIndex].start, newEnd)
            return memo
        } else {
            cancel()
        }
    })

    // 左侧拖拽
    const bindLeft = useDrag(({ movement: [mx], memo = trackList[activeIndex].start, active, cancel }) => {
        active ? disableScroll() : enableScroll()
        if (activeIndex >= 0 && active) {
          const newStart = memo + pxToSecond(mx, secondWidth)
          updateTrackList(newStart, trackList[activeIndex].end)
          return memo
        } else {
            cancel()
        }
    })

    // 整体拖拽
    const bindDrag = useDrag(({ movement: [mx], active, memo = trackList[activeIndex], cancel }) => {
        // 如果拖动中，禁用滚动，否则启用滚动
        active ? disableScroll() : enableScroll()
        const { start, end } = memo
        // s = s / w
        const newStart = start + pxToSecond(mx, secondWidth)
        const newEnd = end + pxToSecond(mx, secondWidth)
        const curOffsetX = end - start
        
        if (active) {
            // 更新原始轨道列表
            updateOriginTrackList(activeIndex, newStart, newEnd)
        } else {
            let prevStartIndex = -1
            let nextStartTime = -1
        
            // 查找停留新开始位置之前的轨道
            trackList.forEach((item, index) => {
                if (item.end <= newStart) prevStartIndex = index
            })
            prevStartIndex = prevStartIndex > -1 ? prevStartIndex : activeIndex
            const nextTrack = trackList[prevStartIndex + 1]
            // 下一个轨道存在
            if (nextTrack) {
                nextStartTime = nextTrack.start
                const offset = prevStartIndex > 0 ? nextStartTime - trackList[prevStartIndex].end : trackList[0].end - trackList[0].start
        
                // 检查新轨道是否可以放置
                const canPlace = trackList.every((track, index) => {
                    if (index === activeIndex && newStart >= 0) return true
                    return newStart >= track.end || newEnd <= track.start
                })
        
                // 如果偏移量足够且可以放置，则更新原始轨道列表
                if (offset >= curOffsetX && canPlace) {
                    updateOriginTrackList(activeIndex, newStart, newEnd)
                } else {
                    updateOriginTrackList(activeIndex, start, end)
                }
            }
        }
        return memo
    })

    return <div className='trackList'>
        {
            trackList.map((item, index) => {
                return <div key={item.name} className="trackItemWrap" style={{ left: `${item.start * secondWidth}px` }}>
                <div {...bindDrag()} style={{ width: `${(item.end - item.start) * secondWidth}px`}} onClick={(e: any) => handleClick(index, e)} className='trackItem' key= {item.name}>  {item.name}
                    </div>
                    {
                        activeIndex === index && <>
                            <i {...bindLeft()} className="trackItemActive left"></i>
                            <i {...bindRight()} className="trackItemActive right"></i>
                        </>
                    }
                </div>
            })
        }
    </div>
}

export default Index